<template>
  <div class='page-content'>

    <!-- 工具栏区域 -->
    <table-bar :showTop="false"
               :columns="columns"
               @changeColumn="changeColumn">
      <!-- 条件查询区域 -->
      <div slot="top">
        <el-form label-width="70px">

          <el-row :gutter="20">
            <el-col :xs="24"
                    :sm="14"
                    :lg="8">
              <el-form-item label="名称：">
                <el-input v-model="queryForm.kw"
                          placeholder="输入流程名称或流程负责人查询"></el-input>
              </el-form-item>
            </el-col>

            <el-row :xs="24"
                    :sm="12"
                    :lg="6"
                    style="float: right; margin-right: 10px;">
              <el-button type="primary"
                         @click="query">搜索</el-button>
              <el-button>重置</el-button>
            </el-row>
          </el-row>
        </el-form>
      </div>
      <!-- 左侧按钮 -->
      <div slot="bottom">
        <el-button type="primary"
                   plain
                   @click="showAddDialog">新增批次</el-button>
        <el-button type="danger"
                   plain
                   @click="delAll">批量删除</el-button>
        <el-button type="success"
                   plain>导入</el-button>
        <el-button type="success"
                   plain>导出</el-button>
      </div>

    </table-bar>

    <!-- 表格区域 -->
    <the-table :data="batchList"
               :showPage="false"
               @getDataBySelectBox="handleSelectionChange"
               ref="table">
      <el-table-column type="selection"
                       width="55"></el-table-column>

      <el-table-column label="序号"
                       type="index"
                       v-if="columns[0].show" />
      <el-table-column label="加工批次"
                       prop="id"
                       v-if="columns[1].show" />
      <el-table-column label="屠宰批次"
                       prop="shBatch"
                       v-if="columns[2].show" />
      <el-table-column label="经手人"
                       prop="processPrincipal"
                       v-if="columns[3].show" />
      <el-table-column label="加工流程名"
                       prop="processName"
                       v-if="columns[4].show" />
      <el-table-column label="加工日期"
                       prop="processTime"
                       v-if="columns[5].show" />
      <el-table-column label="创建时间"
                       prop="gmtCreate"
                       v-if="columns[6].show" />

      <el-table-column label="修改时间"
                       prop="gmtModified"
                       v-if="columns[7].show" />
      <el-table-column label="操作"
                       fixed="right"
                       width="200px"
                       v-if="columns[8].show">
        <template slot-scope="scope">
          <el-button type="text"
                     icon="el-icon-document"
                     @click="showDetailsDialog(scope.row)">
            详情
          </el-button>
          <el-button type="text"
                     icon="el-icon-edit"
                     @click="showEditDialog(scope.row)">
            编辑
          </el-button>
          <el-button type="text"
                     style="color: #FA6962"
                     icon="el-icon-delete"
                     @click="delById(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </the-table>

    <!-- 分页器区域 -->
    <el-pagination layout="total, sizes, prev, pager, next, jumper"
                   :page-sizes="[5, 8, 10, 15]"
                   :page-size="pageSize"
                   :current-page="pageNum"
                   :total="total"
                   @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   class="page">
    </el-pagination>

    <!-- 批次详情对话框 -->
    <el-dialog :visible.sync="detailsDialog"
               width="70%">
      <div slot="title">
        <span>批次详细信息</span>
      </div>
      <div>
        <el-divider>产品详情</el-divider>
        <the-table :data="productDetails"
                   :showPage="false">
          <el-table-column label="产品编号"
                           prop="productId" />
          <el-table-column label="产品名"
                           prop="processingType" />
          <el-table-column label="产品规格"
                           prop="productSpecification" />
          <el-table-column label="产品数量"
                           prop="amount" />
        </the-table>
        <el-divider>材料详情</el-divider>
        <the-table :data="materialDetails"
                   :showPage="false">
          <el-table-column label="材料名称"
                           prop="materialName" />
          <el-table-column label="材料规格"
                           prop="specifications" />
          <el-table-column label="材料数量"
                           prop="materialAmount" />
        </the-table>
      </div>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="detailsDialog = false">取 消</el-button>
        <el-button type="primary"
                   @click="detailsDialog = false">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改批次对话框 -->
    <!--  <el-dialog title="修改加工批次"
               :visible.sync="addDialog"
               @close="dialogClose('editFormRef')"
               width="
               30%">
      <el-form :model="editForm"
               :rules="editFormRules"
               ref="editFormRef"
               label-width="100px">
        <el-form-item label="流程名称"
                      prop="processName">
          <el-input v-model="editForm.processName"
                    clearable></el-input>
        </el-form-item>
        <el-form-item label="流程负责人"
                      prop="principal">
          <el-input v-model="editForm.principal"
                    clearable></el-input>
        </el-form-item>
        <el-form-item label="流程描述"
                      prop="processDescribe">
          <el-input type="textarea"
                    clearable
                    v-model="editForm.processDescribe"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary"
                   @click="update">确 定</el-button>
      </span>
    </el-dialog> -->

    <!-- 新增&修改批次对话框 -->
    <el-dialog :title="isShowAddForm?'新增批次':'修改批次'"
               :visible.sync="addDialog"
               width="80%">
      <el-form ref="addFormRef"
               :model="addForm"
               :rules="addFormRules"
               inline
               label-width="90px">
        <el-form-item label="屠宰批次"
                      required>
          <el-select v-model="addForm.shBatch"
                     filterable
                     placeholder="请关联所属屠宰批次">
            <el-option v-for="(item,index) in shBatchOptions"
                       :key="item.shBatch + index"
                       :label="item.shBatch"
                       :value="item.shBatch"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="加工流程"
                      required>
          <el-select v-model="selectProcessId"
                     @change="processOptionsChange"
                     filterable
                     placeholder="请关联加工流程">
            <el-option v-for="(item,index) in processOptions"
                       :key="item.processId + index"
                       :label="item.processId"
                       :value="item">
            </el-option>
            <!-- <template>
              <div class="el-selec-tinner">
                <el-input v-model="addForm.processId"></el-input>
              </div>
            </template> -->
          </el-select>
        </el-form-item>
        <el-form-item label="加工日期">
          <el-date-picker v-model="addForm.processTime"
                          type="date"
                          value-format="yyyy-MM-dd mm:hh:ss"
                          placeholder="选择加工日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="加工厂编号"
                      prop="processingNum"
                      v-if="isShowAddForm">
          <el-input v-model="addForm.processingNum"
                    placeholder="请自定义加工厂编号0~99">
          </el-input>
        </el-form-item>
        <el-form-item label="经手人"
                      prop="processPrincipal">
          <el-input v-model="addForm.processPrincipal"
                    placeholder="请输入经手人">
          </el-input>
        </el-form-item>
        <el-divider>产品详情</el-divider>

        <el-form-item label="产品名"
                      prop="processingType">
          <el-input v-model="addForm.processingType"
                    placeholder="请输入产品名">
          </el-input>
        </el-form-item>
        <el-form-item label="产品规格"
                      prop="productSpecification">
          <el-input v-model="addForm.productSpecification"
                    placeholder="请输入产品规格">
          </el-input>
        </el-form-item>
        <el-form-item label="产品数量"
                      prop="amount">
          <el-input v-model.number="addForm.amount"
                    placeholder="请输入产品数量">
          </el-input>
        </el-form-item>
        <el-form-item label="产品编号"
                      prop="productId">
          <el-input v-model="addForm.productId"
                    placeholder="请输入产品编号">
          </el-input>
        </el-form-item>
        <el-divider>材料详情</el-divider>
        <div v-for="(item,index) in addForm.processingBatchDtos"
             :key="index">
          <!-- <span class="batch-item">{{index+1}}：</span> -->
          <el-form-item label="材料名称"
                        required>
            <el-input v-model="addForm.processingBatchDtos[index].materialName">
            </el-input>
          </el-form-item>
          <el-form-item label="规格"
                        required>
            <el-select v-model="addForm.processingBatchDtos[index].specifications"
                       filterable
                       placeholder="请选择规格">
              <el-option v-for="item in specificationsAddList"
                         :key="item"
                         :label="item"
                         :value="item">
              </el-option>
              <template>
                <div class="el-selec-tinner">
                  <el-input v-model="addForm.processingBatchDtos[index].specifications"></el-input>
                </div>
              </template>
            </el-select>
            </el-input>
          </el-form-item>
          <el-form-item label="材料数量"
                        required>
            <el-input v-model="addForm.processingBatchDtos[index].materialAmount">
            </el-input>
          </el-form-item>

          <el-button icon="el-icon-delete"
                     @click="removeBatchItem(index)">
          </el-button>
        </div>

      </el-form> <span slot="footer"
            class="dialog-footer">
        <el-button @click="AddBatchItem">新增材料</el-button>
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary"
                   @click="add">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { changeColumn, pagination, dialogClose, multipleSelection, queryForm } from '@/api/mixin'
import { dateShorter } from '@/utils/utils'

export default {
  name: "BatchManage_P",
  meta: {
    title: "加工批次管理",
  },
  mixins: [changeColumn, pagination, dialogClose, queryForm, multipleSelection,
  ],
  created () {
    this.getBatchList()
  },
  computed: {
    select_processingId () {
      return this.$store.state.Usersetting.ProcessInfo.processingId
    }
  },
  data () {
    return {
      columns: [
        { name: "序号", show: true },
        { name: "加工批次", show: true },
        { name: "屠宰批次", show: true },
        { name: "经手人", show: true },
        { name: "加工流程名", show: true },
        { name: "加工日期", show: true },
        { name: "创建时间", show: true },
        { name: "修改时间", show: true },
        { name: "操作", show: true },
      ],
      batchList: [{
        batchId: "",//加工批次 id
        shBatch: "",//屠宰批次
        processingId: "",//所属加工厂 id
        processName: "",//-加工流程名称
        processDescribe: "",//-加工流程描述
        processingTime: "",//加工日期
        processId: "",//加工流程 id
        technologyId: "",//工艺 id
        processPrincipal: ""//-该天-加工流程负责人
      }],
      batchDetailsList: [{
        batchId: "",
        processDescribe: "",
        processId: "",
        processName: "",
        processPrincipal: "",
        processingId: "",
        processingTime: "",
        shBatch: "",
        technologyId: "",
      }],
      //新增流程对话框
      addDialog: false,
      detailsDialog: false,
      // 条件查询参数
      queryForm: {
        kw: ''
      },
      id: '',//批次id
      editFormRules: {
        technologyName: [{ required: true, message: '请输入工艺名称', trigger: 'blur' }, { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }],
        technologyDescribe: [{ required: true, message: '请输入工艺描述', trigger: 'blur' }],
        processId: [{ required: true }]
      },
      addFormRules: {
        processId: [],
        technologyId: [],
        // processId: [{ required: true, message: '请选择流程', trigger: 'blur' }],
        // technologyId: [{ required: true, message: '请选择工艺', trigger: 'blur' }],
        shBatch: [{ required: true, message: '请选择屠宰批次', trigger: 'blur' }],
        processingTime: [{ required: true, message: '请选择加工日期', trigger: 'blur' }],
        principal: [{ required: true, message: '请输入当天负责人', trigger: 'blur' }, { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }],

      },
      addForm: {
        amount: '',//产品数量-
        processId: '',//关联流程-
        processName: '',//关联流程后填充-
        processPrincipal: '',//关联流程后填充-
        processTime: '',//关联流程后填充-
        processingBatchDtos: [
          {
            materialAmount: '',//材料数量
            materialName: '',//材料名称
            specifications: ''//规格
          }
        ],
        processingId: '',//工厂-
        processingNum: '',//加工厂编号-
        processingType: '',//产品名-
        productId: '',//产品编号-
        productSpecification: '',//产品规格
        shBatch: ''//屠宰批次-
      },
      selectProcessId: {},
      isShowAddForm: true,
      // 流程 屠宰列表
      specificationsAddList: ['200g/盒', '500g/盒', '1kg/盒', '1t/盒'],
      processOptions: [],
      shBatchOptions: [],
      productDetails: [{
        productId: '37',
        processingType: '卤香肉鸽腿',
        productSpecification: '500g/盒',
        amount: '300'
      }],
      materialDetails: [
        {
          materialAmount: 300,
          materialName: '酱油',
          specifications: '500ml/瓶'
        },
        {
          materialAmount: 700,
          materialName: '蚝油',
          specifications: '300ml/瓶'
        },
        {
          materialAmount: 200,
          materialName: '配菜',
          specifications: '500g/袋'
        },
        {
          materialAmount: 400,
          materialName: '料酒',
          specifications: '700ml/瓶'
        },
      ]
    }
  },
  methods: {
    //展示流程详情对话框
    async showDetailsDialog ({ id }) {

      const { data: res } = await this.$http.get(`/processing/processing-batch/info/${id}`)

      if (res.statusCode !== 20000) return this.$message.error('获取流程详情失败')



      this.productDetails = [res.data]
      this.materialDetails = res.data.processingBatches

      this.detailsDialog = true
    },
    getList () {
      this.getBatchList()
    },
    // 分页
    async getBatchList () {
      const { data: res } = await this.$http.get(`/processing/processing-batch/page/${this.pageNum}/${this.pageSize}`, { params: { processingId: this.select_processingId } })
      if (res.statusCode !== 20000) return this.$message.error('获取批次列表失败')

      dateShorter(res.data.records, 'gmtCreate')
      dateShorter(res.data.records, 'gmtModified')
      dateShorter(res.data.records, 'processTime')
      this.batchList = res.data.records
      this.total = res.data.total
    },
    // 条件查询
    async query () {
      const { data: res } = await this.$http.get(`/processing/processing-batch/like/${this.queryForm.kw}/${this.pageNum}/${this.pageSize}`, { params: { processingId: this.select_processingId } })
      if (res.statusCode !== 20000) return this.$message.error('查询失败')

      // console.log(res.data.records, 'query');
      dateShorter(res.data.records, 'gmtCreate')
      dateShorter(res.data.records, 'gmtModified')
      dateShorter(res.data.records, 'processingTime')
      this.batchList = res.data.records
      this.total = res.data.total
      this.$message.success('查询成功')
    },
    /* 删除 */
    delById ({ id }) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`/processing/processing-batch/deletion/${id}`)

        if (res.statusCode !== 20000) return this.$message.error('删除失败')

        this.$message.success('删除成功')
        this.getBatchList()

      }).catch(() => {
        this.$message('已取消删除!')
      })

    },
    delAll () {
      if (this.multipleSelection.length === 0)
        return this.$message.error('未选中记录')

      this.$confirm('此操作将永久删除这些记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const ids = []

        this.multipleSelection.forEach(x => ids.push(x.id))

        const { data: res } = await this.$http.delete(`/processing/processing-batch/deletion/batch`, {
          data: ids,
          headers: {
            'Content-Type': 'application/json'
          },
        })//参数置于请求体

        if (res.statusCode !== 20000) return this.$message.error('删除失败')

        this.$message.success('批量删除成功')
        this.getBatchList()

      })
        .catch(() => {
          this.$message('已取消删除!')
        })

    },
    /* 编辑 */
    async showEditDialog ({ id }) {
      //保存id
      this.id = id
      //获取最新的记录
      const { data: res } = await this.$http.get(`/processing/processing-batch/info/${id}`)
      if (res.statusCode !== 20000) return this.$message.error('获取最新的批次记录失败')

      //保存信息
      const { processingType, productSpecification, amount, productId, processingBatches } = res.data || {}
      this.addForm.processingBatchDtos = processingBatches
      this.addForm.processingType = processingType
      this.addForm.productSpecification = productSpecification
      this.addForm.amount = amount
      this.addForm.productId = productId
      // 显示
      this.isShowAddForm = false
      this.addDialog = true
      /* 
      {
        amount: '',//产品数量-
        processId: '',//关联流程-
        processName: '',//关联流程后填充-
        processPrincipal: '',//关联流程后填充-
        processTime: '',//关联流程后填充-
        processingBatchDtos: [
          {
            materialAmount: '',//材料数量
            materialName: '',//材料名称
            specifications: ''//规格
          }
        ],
        processingId: '',//工厂-
        processingNum: '',//加工厂编号-
        processingType: '',//产品名-
        productId: '',//产品编号-
        productSpecification: '',//产品规格
        shBatch: ''//屠宰批次-
      }
      */
    },
    update () {
      // 表单验证
      this.$refs.editFormRef.validate(async flag => {
        if (!flag)
          return this.$message.error('请正确填写表单')
        // 发送请求
        const { data: res } = await this.$http.put(`/processing/processing-batch/update/${this.batchId}`, this.editForm)
        if (res.statusCode !== 20000) return this.$message.error('修改失败')

        //刷选列表
        this.getBatchList()


        // 关闭
        this.addDialog = false
        this.$message.success('修改成功')



      })





    },
    /* 编辑 */

    /* 新增 */
    //展示新增流程对话框
    async showAddDialog () {
      // 获取工厂id
      this.addForm.processingId = this.select_processingId
      // 获取流程列表
      const { data: res1 } = await this.$http.get(`/processing/processing-flow/page/1/101`, { params: { processingId: this.select_processingId } })
      if (res1.statusCode !== 20000) return this.$message.error('获取加工流程列表失败')

      this.processOptions = res1.data.records



      //获取屠宰列表
      const { data: res2 } = await this.$http.get(`/pigeon/t-slaughterhouse-batch-info/getPageTO/1/100`)
      if (res2.statusCode !== 20000) return this.$message.error('获取屠宰批次列表失败')
      this.shBatchOptions = res2.data.records


      this.addDialog = true
    },
    async add () {
      this.$refs.addFormRef.validate(async flag => {
        if (!flag)
          return this.$message.error('请正确填写表单')
        const { data: res } = await this.$http.post(`/processing/processing-batch/`, this.addForm)
        if (res.statusCode !== 20000) return this.$message.error('添加失败')

        this.$message.success('添加成功')
        this.getBatchList()
        this.addDialog = false
      })

    },
    AddBatchItem () {
      this.addForm.processingBatchDtos.push({
        materialAmount: '',//材料数量
        materialName: '',//材料名称
        specifications: ''//规格
      })
    },
    removeBatchItem (index) {
      this.addForm.processingBatchDtos.splice(index, 1)
    },
    /* 新增 */
    // 选中流程填充表单相关信息
    processOptionsChange ({ processName, processId }) {
      this.addForm.processName = processName//关联流程后填充
      this.addForm.processId = processId//关联流程后填充
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  margin-top: 6px;
  text-align: center;
}
.dialog_title {
  display: flex;
  span {
    flex: 1;
  }
}
</style>